/*
* SIP XML Scenario Maker

* Copyright 2008 Rachid El Khayari

*

* This file is part of SIP XML Scenario Maker (SXSM).

*

* SXSM is free software: you can redistribute it and/or modify

* it under the terms of the GNU General Public License as published by

* the Free Software Foundation, either version 3 of the License, or

* (at your option) any later version.

*

* SXSM is distributed in the hope that it will be useful,

* but WITHOUT ANY WARRANTY; without even the implied warranty of

* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the

* GNU General Public License for more details.

*

* You should have received a copy of the GNU General Public License

* along with SXSM.  If not, see <http://www.gnu.org/licenses/>.

*/
#include <QtGui>
#include <QNetworkInterface>
#include <QHostAddress>
#include <QAssistantClient>
#include <QAction>
#include <QMenu>
#include <QDialog>
#include <QGridLayout>
#include <QLineEdit>
#include <QPushButton>
#include <QLabel>
#include <QStringList>
#include <QSettings>
#include <QComboBox>
#include <QTextEdit>
#include <QSpinBox>
#include <QListWidget>
#include <QProcess>
#include <QProgressBar>
#include <QPixmap>
#include <QSplashScreen>
#include <QNetworkInterface>
#include <QHostAddress>
#include <QRadioButton>
#include <QTabWidget>
#include "mainwindow.h"
/*!
* The constructor of the MainWindow class 
*/
 MainWindow::MainWindow()
 {
	/*!
	* Creates Actions and Menus.
	*/
	createActions();
	createMenus();
	/*!
 	* Loads settings parameters.
 	*/
	QSettings settings("RashSoft","sxsm");
	SIPpPath = settings.value("SIPp Path").toString();
	DataDir = settings.value("datadir").toString();
	ScenarioDir = settings.value("scenariodir").toString();
	MessageDir = settings.value("messagedir").toString();
	CSVDir = settings.value("csvdir").toString();
	LogDir = settings.value("logdir").toString();
	/*!
	* Starts initialization of assistant.
	*/
	initializeAssistant();
	/*!
	* Displays readiness of application
	*/
	statusBar()->showMessage(tr("ready"));
 }

void MainWindow::closeEvent(QCloseEvent *)
{
	/*!
	* Makes sure that assistant is terminated when main application is closed.
	*/
	if (assistantClient){
		assistantClient->closeAssistant();
	}
	/*!
	* Makes sure that child Process is terminated when main application is closed.
	*/
	if (myProcess){
		myProcess->close();
	}
}

void MainWindow::assistant()
{
	/*!
	* Opens an instance of application's assistant.
	*/
	assistantClient->openAssistant();
}


/*!
* Defines actions that can be accessed via keyboard shortcuts and menu entries.
*/
void MainWindow::createActions()
 {
	/*!
	* Creates settings action and connects it to settings slot.
	*/
	settingsAct = new QAction(tr("&Settings"), this);
	settingsAct->setShortcut(tr("Ctrl+S"));
	settingsAct->setStatusTip(tr("Configure settings"));
	connect(settingsAct, SIGNAL(triggered()), this, SLOT(settings()));
	/*!
	* Creates message mode action and connects it to message mode slot.
	*/
	messagesAct = new QAction(tr("&Message editor"), this);
	messagesAct->setShortcut(tr("Ctrl+M"));
	messagesAct->setStatusTip(tr("Configure message layout"));
	connect(messagesAct, SIGNAL(triggered()), this, SLOT(messages()));
	/*!
	* Creates exit action and connects it to close slot.
	*/
	exitAct = new QAction(tr("E&xit"), this);
	exitAct->setShortcut(tr("Ctrl+Q"));
	exitAct->setStatusTip(tr("Exit the application"));
	connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
	/*!
	* Creates shoot mode action and connects it to shoot mode slot.
	*/
	shootModeAct = new QAction(tr("Sh&oot mode"), this);
	shootModeAct->setShortcut(tr("Ctrl+O"));
	shootModeAct->setStatusTip(tr("Start shoot mode"));
	connect(shootModeAct, SIGNAL(triggered()), this, SLOT(shootMode()));
	/*!
	* Creates about action and connects it to about slot.
	*/
	aboutAct = new QAction(tr("&About"), this);
	aboutAct->setStatusTip(tr("Show the application's About box"));
	connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
	/*!
	* Creates aboutQt action and connects ist to aboutQt slot.
	*/
	aboutQtAct = new QAction(tr("About &Qt"), this);
	aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
	connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
	connect(aboutQtAct, SIGNAL(triggered()), this, SLOT(aboutQt()));
	/*!
	* Creates assistant action and connects it to assistant slot.
	*/
	assistantAct = new QAction(tr("Help Contents"), this);
	assistantAct->setShortcut(tr("F1"));
	connect(assistantAct, SIGNAL(triggered()), this, SLOT(assistant()));
 }

/*!
* defines The menu entries of the application's menu 
* and to which actions they are mapped.
*/
 void MainWindow::createMenus()
 {
	/*!
	* Creates file menu.
	*/
	fileMenu = menuBar()->addMenu(tr("&File"));
	fileMenu->addAction(shootModeAct);
	fileMenu->addAction(messagesAct);
	fileMenu->addSeparator();
	fileMenu->addAction(settingsAct);
	fileMenu->addAction(exitAct);
	/*!
	* Creates help menu.
	*/
	helpMenu = menuBar()->addMenu(tr("&Help"));
	helpMenu->addAction(assistantAct);
	helpMenu->addSeparator();
	helpMenu->addAction(aboutAct);
	helpMenu->addAction(aboutQtAct);
 } 

void MainWindow::initializeAssistant()
{
	/*!
	* Initializes assistant with correct profile.
	*/
	QString tmpPath = DataDir;
	tmpPath.append("help/sxsm_profile.adp");
	assistantClient = new QAssistantClient(QLibraryInfo::location(QLibraryInfo::BinariesPath), this);
	QStringList arguments;
	arguments << "-profile" << tmpPath;
	assistantClient->setArguments(arguments);
}


/*!
* Creates the settings dialog, where programm specififc paramaeters can be changed.
*/
 void MainWindow::settings()
 {		
		/*!
		* Loads settings.
		*/	
		QString sipptmpPath = SIPpPath;
		QString datatmpPath = DataDir;
		QString messagetmpPath = MessageDir;
		QString scenariotmpPath = ScenarioDir;
		QString csvtmpPath = CSVDir;
		QString logtmpPath = LogDir;
		/*!
		* Displays settings in new Dialog.
		*/
		settingsDialog = new QDialog(this);
		settingsDialog->setWindowTitle("Settings");
		QGridLayout *settingsLayout = new QGridLayout;
		sippPathLabel = new QLabel(tr("SIPp Path:"));
		dataPathLabel = new QLabel(tr("Data Path:"));
		messagePathLabel = new QLabel(tr("Message Path:"));
		scenarioPathLabel = new QLabel(tr("Scenario Path:"));
		csvPathLabel = new QLabel(tr("CSV Path:"));
		logPathLabel = new QLabel(tr("Logfile Path:"));
		sippPath = new QLineEdit(sipptmpPath);
		dataPath = new QLineEdit(datatmpPath);
		messagePath = new QLineEdit(messagetmpPath);
		scenarioPath = new QLineEdit(scenariotmpPath);
		csvPath = new QLineEdit(csvtmpPath);
		logPath = new QLineEdit(logtmpPath);
		settingsSaveButton = new QPushButton(tr("Save"));
		settingsLayout->addWidget(sippPathLabel,0,0);
		settingsLayout->addWidget(sippPath,0,1,1,4);
		settingsLayout->addWidget(dataPathLabel,1,0);
		settingsLayout->addWidget(dataPath,1,1,1,4);
		settingsLayout->addWidget(messagePathLabel,2,0);
		settingsLayout->addWidget(messagePath,2,1,1,4);
		settingsLayout->addWidget(scenarioPathLabel,3,0);
		settingsLayout->addWidget(scenarioPath,3,1,1,4);
		settingsLayout->addWidget(csvPathLabel,4,0);
		settingsLayout->addWidget(csvPath,4,1,1,4);
		settingsLayout->addWidget(logPathLabel,5,0);
		settingsLayout->addWidget(logPath,5,1,1,4);
		settingsLayout->addWidget(settingsSaveButton,6,4);
		settingsDialog->setLayout(settingsLayout);
		connect(settingsSaveButton, SIGNAL(clicked()), this, SLOT(saveSettings()));	
		settingsDialog->resize(600,100);
		settingsDialog->setModal(true);
		settingsDialog->setSizeGripEnabled(false);
		settingsDialog->show();
 }

/*!
* creates the message editor dialog, where SIP messages can be created and modified.
*/
 void MainWindow::messages()
 {
		messagesDialog = new QDialog(this);
		messagesDialog->setWindowTitle("Message editor");
		messageSetSelect=new QComboBox();
		messageSetSelect->addItem(tr("Select message set"));
		messageSetSelect->addItem(tr("Create new message set..."));
		/*!
		* Initiates loading of message set list.
		*/
		if(!(loadMessageSetList())){
		QMessageBox::StandardButton msgBox;	
		msgBox = QMessageBox::critical(this, tr("Message set list not loaded"),
                      tr("Couldn't find messageset.dat in message dir."),
                      QMessageBox::Ok);
		}
		messageTypeTemplateSelect=new QComboBox();
		messageTypeTemplateSelect->setDisabled(true);
		messageTypeTemplateSelect->addItem(tr("Select message type"));
		messageTypeTemplateSelect->addItem(tr("Create new message type..."));
		messageTemplateSelect = new QComboBox();
		messageTemplateSelect->setDisabled(true);
		messageTemplateSelect->addItem(tr("Select message"));
		messageTemplateSelect->addItem(tr("Create new message..."));
		

		messageTemplateStandardLabel = new QLabel(tr("Message Headers"));
		headerFields= new QTextEdit();
		headerFields->setDisabled(true);
		messageSaveButton = new QPushButton(tr("Save"));
		
		QGridLayout *messagesLayout = new QGridLayout;
		//messagesLayout->setColumnStretch(0,2);
		messagesLayout->addWidget(messageSetSelect,0,0,1,3);
		messagesLayout->addWidget(messageTypeTemplateSelect,1,0,1,3);
		messagesLayout->addWidget(messageTemplateSelect,2,0,1,3);
		messagesLayout->addWidget(messageTemplateStandardLabel,3,0);
		messagesLayout->addWidget(headerFields,4,0,1,3);
		messagesLayout->addWidget(messageSaveButton,5,2);
		messagesDialog->setLayout(messagesLayout);
		connect(messageSetSelect, SIGNAL(activated(const QString &)), this, SLOT(viewMessageTypeList()));
		connect(messageTypeTemplateSelect, SIGNAL(activated(const QString &)), this, SLOT(viewMessageList()));
		connect(messageTemplateSelect, SIGNAL(activated(const QString &)), this, SLOT(viewMessage()));
		connect(messageSaveButton, SIGNAL(clicked()), this, SLOT(saveMessage()));
		messagesDialog->resize(800,600);
		messagesDialog->setModal(true);
		messagesDialog->setSizeGripEnabled(false);
		messagesDialog->show();
 }

void MainWindow::makeCreateDialog(int classifier)
{
	/*!
	* Displays a generic create dialog.
	*/
	createDialog = new QDialog(this);
	createDialog->setWindowTitle("Create dialog");
	createDialog->resize(400,150);
	createDialog->setModal(true);
	createDialog->setSizeGripEnabled(false);
	QGridLayout *createLayout = new QGridLayout;
	/*!
	* According to selected classifier type of create dialog is chosen.
	*/
	switch(classifier){
		case 0:
			/*!
			* Classifier "0" creates a dialog for new message sets.
			*/
			newMessageSetLine = new QLineEdit(tr("Enter new set name"));
			newMessageSetButton = new QPushButton(tr("Create new set"));
			createLayout->addWidget(newMessageSetLine,0,0,1,2);
			createLayout->addWidget(newMessageSetButton,1,1);
			connect(newMessageSetButton, SIGNAL(clicked()), this, SLOT(makeSet()));
			break;
		case 1:
			/*!
			* Classifier "1" creates a dialog for new message types.
			*/
			newMessageTypeLine = new QLineEdit(tr("Enter new type name"));
			newMessageTypeButton = new QPushButton(tr("Create new type"));
			createLayout->addWidget(newMessageTypeLine,0,0,1,2);
			createLayout->addWidget(newMessageTypeButton,1,1);
			connect(newMessageTypeButton, SIGNAL(clicked()), this, SLOT(makeType()));
			break;
		case 2:
			/*!
			* Classifier "2" creates a dialog for new messages.
			*/
			newMessageTemplateLine = new QLineEdit(tr("Enter new message name"));
			newMessageTemplateButton = new QPushButton(tr("Create new message"));
			createLayout->addWidget(newMessageTemplateLine,0,0,1,2);
			createLayout->addWidget(newMessageTemplateButton,1,1);
			connect(newMessageTemplateButton, SIGNAL(clicked()), this, SLOT(makeMessage()));
			break;
		default:
			/*!
			* Default handles invalid classifiers (which should never be created)
			*/
			QMessageBox::StandardButton msgBox;	
			msgBox = QMessageBox::critical(this, tr("Classifier incorrect"),
                    	tr("Severe Error: passed classifier not assigned!"),
                      	QMessageBox::Ok);
	}
	createDialog->setLayout(createLayout);
	createDialog->show();
}

void MainWindow::shootMode(){
	/*!
	* Creates a dialog in which shoot parameters can be set and shoot process can be started
	*/
	shootDialog = new QDialog(this);
	shootDialog->setWindowTitle("Shoot mode");
	shootDialog->resize(800,600);
	shootDialog->setModal(true);
	shootDialog->setSizeGripEnabled(false);
	shootScenarioSetSelect = new QComboBox();
	shootScenarioSetSelect->addItem(tr("Select scenario set"));
	shootScenarioSelect = new QComboBox();
	shootScenarioSelect->setDisabled(true);	
	shootScenarioSelect->addItem(tr("Select scenario"));
	/*!
	* Initiates loading of scenario set list.
	*/
	if(!(loadScenarioSetList())){
		QMessageBox::StandardButton msgBox;	
		msgBox = QMessageBox::critical(this, tr("Scenario sets not loaded"),
                      tr("Couldn't find scenariossets.dat in scenario dir."),
                      QMessageBox::Ok);
	}
	shootTimeLabel1 = new QLabel(tr("Play scenario "));
	shootTimeLabel2 = new QLabel(tr(" times. With "));
	shootTimeLabel3 = new QLabel(tr(" calls, every "));
	shootTimeLabel4 = new QLabel(tr(" ms."));
	shootNumberOfRounds = new QSpinBox();
	shootNumberOfCallsPerPeriod = new QSpinBox();
	shootPeriod = new QSpinBox();
	shootNumberOfRounds = new QSpinBox();
	shootNumberOfRounds->setMinimum(1);
	shootNumberOfRounds->setMaximum(99999999);
	shootNumberOfRounds->setSingleStep(1);
	shootNumberOfCallsPerPeriod->setMaximum(99999999);
	shootNumberOfCallsPerPeriod->setSingleStep(1);
	shootNumberOfCallsPerPeriod->setMinimum(1);
	shootPeriod->setMaximum(99999999);
	shootPeriod->setMinimum(1000);
	shootPeriod->setSingleStep(100);
	shootAdditionalParametersLabel = new QLabel(tr("Enter additional SIPp Paramaters"));
	shootAdditionalParameters = new QLineEdit();
	shootScenarioAdd = new QPushButton(tr("Add"));
	shootListWidget = new QListWidget();
	shootNumberParameter = new QListWidget();
	shootCallsPerPeriodParam = new QListWidget();
	shootPeriodParam = new QListWidget();
	shootAddiParam = new QListWidget();
	
	QGroupBox *groupBox = new QGroupBox(tr("Targeted usernames"));
	
	scenarioParameterTargetLabel=new QLabel(tr("Targeted username"));
	staticLocalUser = new QRadioButton(tr("Use static username"));
	csvLocalUser = new QRadioButton(tr("Use CSV file as username"));
	staticLocalUserLine = new QLineEdit(tr("username"));
	staticLocalUserLine->setDisabled(true);
	csvLocalUserCombo = new QComboBox();
	csvLocalUserCombo->setDisabled(true);	
	csvLocalUserCombo->addItem(tr("Select CSV file"));
	csvLocalUserCombo->addItem(tr("Create new CSV file"));

	QGridLayout *grid2 = new QGridLayout;

	/*!
	* Initiates loading of CSV list.
	*/
	if(!(loadCSVList())){
		QMessageBox::StandardButton msgBox;	
		msgBox = QMessageBox::critical(this, tr("CSV list not loaded"),
                      tr("Couldn't find csv.dat in csv dir."),
                      QMessageBox::Ok);
	}
	scenarioParameterRemoteIpLabel=new QLabel(tr("Remote IP"));
	scenarioParameterRemoteIpLine=new QLineEdit(tr("localhost"));
	scenarioParameterRemotePortLabel =new QLabel(tr("Remote Port"));
	scenarioParameterRemotePortLine = new QLineEdit(tr("5060"));
	
	scenarioParameterLocalIpLabel = new QLabel(tr("Local IP"));
	scenarioParameterLocalIpCombo = new QComboBox();
	/*!
	* Loads list of available network interfaces.
	*/
	int o=-1;
	QList<QHostAddress> addrlist = QNetworkInterface::allAddresses();
	foreach(QHostAddress addr, addrlist){
		o++;
		QNetworkInterface hop = QNetworkInterface::interfaceFromIndex(o);
		QString tmp_ip = addr.toString();
		scenarioParameterLocalIpCombo->addItem(tmp_ip);
	}

	scenarioParameterLocalPortLabel = new QLabel(tr("Local Port"));
	scenarioParameterLocalPortLine = new QLineEdit(tr("5070"));;


	QLabel *scenarioParameterTransportLabel=new QLabel(tr("Transport"));
	scenarioParameterTransportCombo=new QComboBox();
	scenarioParameterTransportCombo->addItem(tr("UDP"));
	scenarioParameterTransportCombo->addItem(tr("TCP"));
	
	shootListReset = new QPushButton(tr("Clear list"));
	startShootButton = new QPushButton(tr("Start scenarios"));
	
	QGridLayout *shootLayout = new QGridLayout;
	shootLayout->addWidget(shootScenarioSetSelect,0,0,1,2);
	shootLayout->addWidget(shootScenarioSelect,0,3,1,3);
	shootLayout->addWidget(shootTimeLabel1,1,0);
	shootLayout->addWidget(shootNumberOfRounds,1,1);
	shootLayout->addWidget(shootTimeLabel2,1,2);
	shootLayout->addWidget(shootNumberOfCallsPerPeriod,1,3);
	shootLayout->addWidget(shootTimeLabel3,1,4);
	shootLayout->addWidget(shootPeriod,1,5);
	shootLayout->addWidget(shootTimeLabel4,1,6);
	shootLayout->addWidget(shootAdditionalParametersLabel,2,0,1,2);
	shootLayout->addWidget(shootAdditionalParameters,2,2,1,2);
	shootLayout->addWidget(shootScenarioAdd,2,5);
	shootLayout->addWidget(shootListWidget,3,0,1,7);
	
	grid2->addWidget(staticLocalUser, 0, 0, 1, 1);
	grid2->addWidget(csvLocalUser, 0, 2);
	grid2->addWidget(staticLocalUserLine, 1, 0, 1, 1);
	grid2->addWidget(csvLocalUserCombo, 1, 2);
	groupBox->setLayout(grid2);
	shootLayout->addWidget(groupBox,4,1,1,3);	

	shootLayout->addWidget(scenarioParameterRemoteIpLabel, 5, 0);
	shootLayout->addWidget(scenarioParameterRemoteIpLine, 5, 1);
	shootLayout->addWidget(scenarioParameterRemotePortLabel, 5, 2);
	shootLayout->addWidget(scenarioParameterRemotePortLine, 5, 3);
	shootLayout->addWidget(scenarioParameterLocalIpLabel, 6, 0);
	shootLayout->addWidget(scenarioParameterLocalIpCombo, 6, 1);
	shootLayout->addWidget(scenarioParameterLocalPortLabel, 6, 2);
	shootLayout->addWidget(scenarioParameterLocalPortLine, 6, 3);
	shootLayout->addWidget(scenarioParameterTransportLabel, 7, 0);
	shootLayout->addWidget(scenarioParameterTransportCombo, 7, 1);
	shootLayout->addWidget(shootListReset, 8, 1);
	shootLayout->addWidget(startShootButton, 8, 3);
	connect(shootScenarioSetSelect, SIGNAL(activated(const QString &)), this, SLOT(loadScenarios()));
	connect(shootScenarioAdd, SIGNAL(clicked()), this, SLOT(addScenario()));
	connect(startShootButton, SIGNAL(clicked()), this, SLOT(scenarioShoot()));
	connect(shootListReset, SIGNAL(clicked()), this, SLOT(resetList()));
	connect(staticLocalUser, SIGNAL(toggled(bool)), this, SLOT(reactToUsernameRadios()));
	connect(csvLocalUser, SIGNAL(toggled(bool)), this, SLOT(reactToUsernameRadios()));
	connect(csvLocalUserCombo, SIGNAL(activated(const QString &)), this, SLOT(makeCSVDialog()));
	shootDialog->setLayout(shootLayout);
	shootDialog->show();
}

void MainWindow::reactToUsernameRadios()
{
	/*!
	* Checks if a staic user or a csv list is chosen.
	*/
	if(staticLocalUser->isChecked()){
		staticLocalUserLine->setDisabled(false);
		csvLocalUserCombo->setDisabled(true);
	} else {
		staticLocalUserLine->setDisabled(true);
		csvLocalUserCombo->setDisabled(false);
	}
}


void MainWindow::addScenario()
{
	/*!
	* Appends a chosen scenario file to shoot list.
	*/
	if((shootScenarioSelect->currentIndex() != 0)) {	
		QString itemName=shootScenarioSetSelect->currentText();
		itemName.append("/");
		itemName.append(shootScenarioSelect->currentText());
		itemName.append(".xml");
		new QListWidgetItem(itemName, shootListWidget);
		itemName = shootNumberOfRounds->text();
		new QListWidgetItem(itemName, shootNumberParameter);
		itemName = shootNumberOfCallsPerPeriod->text();
		new QListWidgetItem(itemName, shootCallsPerPeriodParam);
		itemName = shootPeriod->text();
		new QListWidgetItem(itemName, shootPeriodParam);
		itemName = shootAdditionalParameters->text();
		new QListWidgetItem(itemName, shootAddiParam);
	}

}

void MainWindow::resetList()
{
	/*!
	* Clears shoot list.
	*/
	shootListWidget->clear();
}

void MainWindow::scenarioShoot(){
	numberOfScenarios = shootListWidget->count();
	processCounter = 0;
	shootSuccessRate=0;
	if(numberOfScenarios>0){
		if(staticLocalUser->isChecked() || (csvLocalUser->isChecked() && csvLocalUserCombo->currentIndex()>1)) {
			/*!
			* Launches the process dialog and the first process of the shoot list.
			*/
			makeProcessDialog();
			startProcess(processCounter);
			shootProgress->setMaximum(numberOfScenarios);
			shootProgress->setVisible(true);
		} else {
			QMessageBox::StandardButton msgBox;	
			msgBox = QMessageBox::critical(this, tr("Select a target type"),
			tr("Chose either a static username or a csv file as target!"),
			QMessageBox::Ok);
		}
	} else {
		QMessageBox::StandardButton msgBox;
		msgBox = QMessageBox::critical(this, tr("No scenario in list"),
		tr("Add scenarios to the list!"),
		QMessageBox::Ok);
	}
}


void MainWindow::startProcess(int processnr)
{
	/*!
	* Creates new process and creates process parameters from shoot mode settings.
	*/
	killstatus=0;
	processDialog->setWindowTitle(tr("Playing Scenario %1 from  %2").arg(processCounter+1).arg(numberOfScenarios));
	QTableWidgetItem *statusItem = new QTableWidgetItem("Running");
	shootTable->setItem(processCounter, 2, statusItem);
	myProcess = new QProcess(this);
	QString transport_tmp;
	QString remotehost_tmp;
	QString program=SIPpPath;
	QString tmpscenarioname = ScenarioDir;
	QString tmpcsv = CSVDir;
	QString addParams = shootAddiParam->item(processnr)->text();
	tmpscenarioname.append(shootListWidget->item(processnr)->text());
	QStringList arguments;
	remotehost_tmp = scenarioParameterRemoteIpLine->text();
	remotehost_tmp.append(":");
	remotehost_tmp.append(scenarioParameterRemotePortLine->text());
	arguments << remotehost_tmp;
	arguments << "-sf" << tmpscenarioname;
	arguments << "-r" << shootCallsPerPeriodParam->item(processnr)->text();
	arguments << "-rp" << shootPeriodParam->item(processnr)->text();
	arguments << "-m" << shootNumberParameter->item(processnr)->text();
	if(staticLocalUser->isChecked()){
		arguments << "-s" << staticLocalUserLine->text();
	} else if(csvLocalUser->isChecked()){
		tmpcsv.append(csvLocalUserCombo->currentText());
		arguments << "-inf" << tmpcsv;
	}
	arguments << "-i" << scenarioParameterLocalIpCombo->currentText();
	arguments << "-mi" << scenarioParameterLocalIpCombo->currentText();
	arguments << "-p" << scenarioParameterLocalPortLine->text();
	if(scenarioParameterTransportCombo->currentText()=="UDP"){
		transport_tmp="u1";
	} else {
		transport_tmp="t1";
	}
	arguments << "-t" << transport_tmp;
	if(addParams!=""){
		arguments << addParams;
	}
	/*!
	* Starts current process.
	*/
	myProcess->start(program, arguments);
	QTableWidgetItem *pidItem = new QTableWidgetItem(tr("pid:  %1").arg(myProcess->pid()));
	shootTable->setItem(processCounter, 1, pidItem);
	connect(myProcess, SIGNAL(readyReadStandardError()), this, SLOT(printError()));
	connect(myProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(printRunningOutput()));
	connect(myProcess, SIGNAL(finished(int)), this, SLOT(printOutput()));
}

void MainWindow::printOutput()
{
	int eCode = myProcess->exitCode();
	/*!
	* Checks the exit code of currently finished process and recalculates successrate.
	*/
	if(killstatus==0){
		if (eCode==0) {
			shootSuccessRate++;
			QTableWidgetItem *statusItem = new QTableWidgetItem("Succeeded");
			shootTable->setItem(processCounter, 2, statusItem);
		}
		else if (eCode==1){
			QTableWidgetItem *statusItem = new QTableWidgetItem("At least 1 call failed");
			shootTable->setItem(processCounter, 2, statusItem);
		}
		
		else if (eCode==97){
			QTableWidgetItem *statusItem = new QTableWidgetItem("Exit on internal command/global timeout");
			shootTable->setItem(processCounter, 2, statusItem);
		}

		else if (eCode==99){
			QTableWidgetItem *statusItem = new QTableWidgetItem("No calls processed");
			shootTable->setItem(processCounter, 2, statusItem);
		}

		else if (eCode==-1){
			QTableWidgetItem *statusItem = new QTableWidgetItem("Fatal Error");
			shootTable->setItem(processCounter, 2, statusItem);
		}
		else {
			QTableWidgetItem *statusItem = new QTableWidgetItem("Failed");
			shootTable->setItem(processCounter, 2, statusItem);
		}
	}else{
		QTableWidgetItem *statusItem = new QTableWidgetItem("Killed by user");
		shootTable->setItem(processCounter, 2, statusItem);
	}
	QTableWidgetItem *ecodeItem = new QTableWidgetItem(tr("exitCode:  %1").arg(eCode));
	shootTable->setItem(processCounter, 3, ecodeItem);
	/*!
	* Reads standard error and standard output from currently finished process.
	*/
	QString error = myProcess->readAllStandardError();
	QString output = myProcess->readAllStandardOutput();
	shootDefaultMessages->append(output);
	shootErrorMessages->append(error);

	/*!
	* Initiates logging for debug purposes.
	*/
	if(writeLogs()){
		processCounter++;
		shootProgress->setValue(processCounter);
		/*!
		* Starts next process from shoot list if end of list is not yet reached.
		*/
		if(processCounter<shootListWidget->count()){
			startProcess(processCounter);
		}
		/*!
		* Calculates and displays success rate if last process from shoot list is exeuted.
		*/
		if(processCounter==numberOfScenarios){
			float tmpRate = ((static_cast<float>(shootSuccessRate)/numberOfScenarios)*100);
			QString stringRate=(tr("Test finished with %1 \% successfull scenarios.").arg(tmpRate));
			QString ratio=(tr("\n%1 scenarios of %2 scenarios executed.").arg(shootSuccessRate).arg(numberOfScenarios));
			stringRate.append(ratio);
			QMessageBox::StandardButton msgBox;	
			msgBox = QMessageBox::critical(this, tr("Test finished!"),
				stringRate,
				QMessageBox::Ok);
		}
	} else {
		QMessageBox::StandardButton msgBox;	
		msgBox = QMessageBox::critical(this, tr("Couldn't write logs!"),
		tr("Test aborted couldn't save log files in log dir"),
		QMessageBox::Ok);
	}
}


bool MainWindow::writeLogs()
{
	/*!
	* Creates log file.
	*/
	QString tmplog = LogDir;
	QDateTime datetime;
	datetime=QDateTime::currentDateTime();
	tmplog.append(datetime.toString("yy_MM_dd_ss_mm_hh_"));
	QString tmpprocname=shootListWidget->item(processCounter)->text();
	tmpprocname.replace(QString("/"), QString("_"));
	tmpprocname.remove(QString(".xml"));
	tmplog.append(tmpprocname);
	tmplog.append(".log");
	QTableWidgetItem *logItem = new QTableWidgetItem(tmplog);
	shootTable->setItem(processCounter, 4, logItem);
	QFile file(tmplog);
	if (!file.open(QIODevice::WriteOnly | QIODevice::Text)){
		return false;
	}else{
		/*!
		* Writes down default messages into log file.
		*/
		QTextStream out(&file);
		out.setCodec("UTF-8");
		out << shootDefaultMessages->toPlainText();
		file.close();
		
	}
	tmplog=LogDir;
	tmplog.append(datetime.toString("yy_MM_dd_ss_mm_hh_"));
	tmplog.append(tmpprocname);
	tmplog.append(".err");
	QTableWidgetItem *errlogItem = new QTableWidgetItem(tmplog);
	shootTable->setItem(processCounter, 5, errlogItem);
	QFile file2(tmplog);
	if (!file2.open(QIODevice::WriteOnly | QIODevice::Text)){
		return false;
	}else{
		/*!
		* Writes down error messages into log file.
		*/
		QTextStream out(&file2);
		out.setCodec("UTF-8");
		out << shootErrorMessages->toPlainText();
		file2.close();
		return true;
	}
}


void MainWindow::printRunningOutput()
{
	/*!
	* Reads all standard output from running process and displays changes.
	*/
	QByteArray data = myProcess->readAllStandardOutput();
	QString text = QString(data);
	shootDefaultMessages->append(text);
}

void MainWindow::printError()
{
	/*!
	* Reads all error output from running process and displays changes.
	*/
	QByteArray data = myProcess->readAllStandardError();
  	QString text = QString(data);
  	shootErrorMessages->append(text);
}

void MainWindow::makeProcessDialog()
{
	/*!
	* Displays dialog that is shown while processes are running.
	*/
	processDialog = new QDialog(shootDialog);
	processDialog->setModal(true);
	processDialog->setSizeGripEnabled(false);
	QGridLayout *processLayout = new QGridLayout;
	shootErrorMessages = new QTextEdit();
	shootDefaultMessages = new QTextEdit();
	shootTable = new QTableWidget(0,6,this);
	QStringList headers;
	headers << "Scenario name" << "SIPp PID" << "Status" << "exitCode" << "Log file" << "Error Log"; 
	shootTable->setHorizontalHeaderLabels(headers);

	for(int i=0; i< shootListWidget->count(); i++){
		shootTable->setRowCount(i+1);
		QTableWidgetItem *nameItem = new QTableWidgetItem(shootListWidget->item(i)->text());
		shootTable->setItem(i, 0, nameItem);
		QTableWidgetItem *pidItem = new QTableWidgetItem("");
		shootTable->setItem(i, 1, pidItem);
		QTableWidgetItem *statusItem = new QTableWidgetItem("Waiting");
		shootTable->setItem(i, 2, statusItem);
		QTableWidgetItem *ecodeItem = new QTableWidgetItem("");
		shootTable->setItem(i, 3, ecodeItem);
		QTableWidgetItem *logItem = new QTableWidgetItem("");
		shootTable->setItem(i, 4, logItem);
		QTableWidgetItem *errItem = new QTableWidgetItem("");
		shootTable->setItem(i, 5, errItem);
	}

	shootProgress = new QProgressBar();
	shootProgress->setVisible(false);
	processStop = new QPushButton(tr("Stop running process"));
	openLog = new QPushButton(tr("Show selected log file"));
	processLayout->addWidget(shootTable, 0,0,1,4);
	processLayout->addWidget(processStop,1,0,1,1);
	processLayout->addWidget(openLog,1,1,1,1);
	processLayout->addWidget(shootDefaultMessages,2,0,1,2);
	processLayout->addWidget(shootErrorMessages,2,2,1,2);
	processLayout->addWidget(shootProgress, 3,0,1,4);
	processLayout->setRowStretch(2,3);
	processDialog->setLayout(processLayout);
	connect(processStop, SIGNAL(clicked()), this, SLOT(stopProcess()));
	connect(openLog, SIGNAL(clicked()), this, SLOT(loadLogs()));
	processDialog->showMaximized();
}


void MainWindow::loadLogs()
{
	int currentrow = shootTable->currentRow();
	int currentcol = shootTable->currentColumn();
	QString logpath = shootTable->item(currentrow,currentcol)->text();
	if((currentcol>3) && (logpath!="")){
		logDialog = new QDialog(processDialog);
		logDialog->setModal(true);
		logDialog->setSizeGripEnabled(false);
		logDialog->setWindowTitle(logpath);
		QGridLayout *logLayout = new QGridLayout;
		logText = new QTextEdit;
		if(!loadLogFile(logpath)){
			QMessageBox::StandardButton msgBox;	
			msgBox = QMessageBox::critical(this, tr("Couldn't load log file"),
                	tr("An error occured while trying to open log file."),
                	QMessageBox::Ok);
		}else{
			logDialog->resize(800,600);
			logLayout->addWidget(logText, 0,0);
			logDialog->setLayout(logLayout);
			logDialog->show();
		}
	}else{
		QMessageBox::StandardButton msgBox;	
		msgBox = QMessageBox::critical(this, tr("Select a log file"),
                tr("Select a log file, from the table."),
                QMessageBox::Ok);
	}
	/*!
	* comment.
	*/
}

bool MainWindow::loadLogFile(QString logName)
{
	/*!
	* Opens selected log file in read only mode.
	*/
	QFile file(logName);
	if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
         return false;
	}else{
		logText->clear();
		QTextStream in(&file);
		in.setCodec("UTF-8");
		/*!
		* Displays content of selected log file.
		*/
		while (!in.atEnd()) {
			QString line = in.readLine();
			logText->append(line);
		}
		return true;
	}
}

void MainWindow::stopProcess()
{
	/*!
	* kills current process.
	*/
	killstatus=1;
	myProcess->kill();
}

 void MainWindow::about()
 {
	/*!
	* Displays splash screen as about box.
	*/
	QString splashpath = DataDir;
	splashpath.append("splash.JPG");
	QPixmap pixmap(splashpath);
	splash= new QSplashScreen(pixmap);
	splash->show();
 }

 void MainWindow::aboutQt()
 {
		//aboutQt
 }

 
void MainWindow::saveSettings()
{
	/*!
	* Creates instance of application settings and writes down changes.
	*/
	QSettings mysettings("RashSoft","sxsm");
	mysettings.setValue("SIPp Path",sippPath->text());
	mysettings.setValue("datadir",dataPath->text());
	mysettings.setValue("messagedir",messagePath->text());
	mysettings.setValue("scenariodir",scenarioPath->text());
	mysettings.setValue("csvdir",csvPath->text());
	mysettings.setValue("logdir",logPath->text());
	settingsDialog->close();
}

bool MainWindow::loadMessagesList()
{
	/*!
	* Opens selected messages.dat list in read only mode.
	*/
	QString fileName=MessageDir;
	fileName.append(messageSetSelect->currentText());
	fileName.append("/");
	fileName.append(messageTypeTemplateSelect->currentText());
	fileName.append("/messages.dat");
	QFile file(fileName);
	if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
         return false;
	}else{
		/*!
		* Clears message list if it was already filled.
		*/
		headerFields->clear();
		int numberOfEntries = messageTemplateSelect->count();
		if(numberOfEntries>2){
			for(int i=2; i<numberOfEntries; i++){
				messageTemplateSelect->removeItem(2);
			}
		}	
		QTextStream in(&file);
		in.setCodec("UTF-8");
		/*!
		* Adds entries of messages.dat to message list combo.
		*/
		while (!in.atEnd()) {
			QString line = in.readLine();
			messageTemplateSelect->addItem(line);
		}
		return true;
	}
}

bool MainWindow::loadMessageTypeList()
{
	/*!
	* Opens selected messagetype.dat in read only mode.
	*/
	QString fileName=MessageDir;
	fileName.append(messageSetSelect->currentText());
	fileName.append("/messagetype.dat");
	QFile file(fileName);
	if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
         return false;
	}else{
		/*!
		* Clears message type list if it was already filled.
		*/
		int numberOfEntries = messageTypeTemplateSelect->count();
		if(numberOfEntries>2){
			for(int i=2; i<numberOfEntries; i++){
				messageTypeTemplateSelect->removeItem(2);
			}
		}	
		QTextStream in(&file);
		in.setCodec("UTF-8");
		/*!
		* Adds entries of selected messagetype.dat to message type list.
		*/
		while (!in.atEnd()) {
			QString line = in.readLine();
			messageTypeTemplateSelect->addItem(line);
		}
		return true;
	}

}

bool MainWindow::loadMessageSetList()
{
	/*!
	* Opens messageset.dat in read only mode.
	*/
	QString fileName=MessageDir;
	fileName.append("messageset.dat");
	QFile file(fileName);
	if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
         return false;
	}else{
		/*!
		* Clears message set list if it was already filled.
		*/
		int numberOfEntries = messageSetSelect->count();
		if(numberOfEntries>2){
			for(int i=2; i<numberOfEntries; i++){
				messageSetSelect->removeItem(2);
			}
		}
		QTextStream in(&file);
		in.setCodec("UTF-8");
		/*!
		* Adds entries of messageset.dat to mesage set list.
		*/
		while (!in.atEnd()) {
			QString line = in.readLine();
			messageSetSelect->addItem(line);
		}
		return true;
	}
}

void MainWindow::loadScenarios()
{
	/*!
	* Initiates loading of scenario list via method loadScenarioList().
	*/
	if(shootScenarioSetSelect->currentIndex() != 0){
		if(!(loadScenarioList())){
			QMessageBox::StandardButton msgBox;	
			msgBox = QMessageBox::critical(this, tr("Scenario list not loaded"),
                      	tr("Couldn't find scenarios.dat in selected scenario set dir."),
                      	QMessageBox::Ok);
		} else {
			shootScenarioSelect->setDisabled(false);	
		}
	}

}


bool MainWindow::loadScenarioList()
{
	/*!
	* Opens scenarios.dat in read only mode.
	*/
	QString fileName=ScenarioDir;
	fileName.append(shootScenarioSetSelect->currentText());
	fileName.append("/scenarios.dat");
	QFile file(fileName);
	if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
         return false;
	}else{
		/*!
		* Clears scenario list if it was already filled.
		*/
		int numberOfEntries = shootScenarioSelect->count();
		if(numberOfEntries>1){
			for(int i=1; i<numberOfEntries; i++){
				shootScenarioSelect->removeItem(1);
			}
		}
		QTextStream in(&file);
		in.setCodec("UTF-8");
		while (!in.atEnd()) {
			/*!
			* Adds entries of scenarios.dat to scenario list.
			*/
			QString line = in.readLine();
			shootScenarioSelect->addItem(line);
		}
		return true;
	}

}
bool MainWindow::loadCSVList()
{
	/*!
	* Opens csv.dat in read only mode.
	*/
	QString fileName=CSVDir;
	fileName.append("csv.dat");
	QFile file(fileName);
	if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
         return false;
	}else{
		/*!
		* Clears csv list if it was already filled.
		*/
		int numberOfEntries = csvLocalUserCombo->count();
		if(numberOfEntries>2){
			for(int i=2; i<numberOfEntries; i++){
				csvLocalUserCombo->removeItem(2);
			}
		}
		QTextStream in(&file);
		in.setCodec("UTF-8");
		/*!
		* Adds entries of csv.dat to csv list.
		*/
		while (!in.atEnd()) {
			QString line = in.readLine();
			csvLocalUserCombo->addItem(line);
		}
		return true;
	}


}

void MainWindow::makeCSVDialog()
{
	/*!
	* Checks if user chose to create a new csv file.
	*/
	if(csvLocalUserCombo->currentIndex()==1){
		/*!
		* Displays dialog for csv file creation.
		*/
		csvDialog = new QDialog(this);
		csvDialog->setWindowTitle("Create csv dialog");
		csvDialog->resize(480,360);
		csvDialog->setModal(true);
		csvDialog->setSizeGripEnabled(false);
		QGridLayout *csvLayout = new QGridLayout;
		newCSVNameLine = new QLineEdit(tr("Enter csv name"));
		newCSVButton = new QPushButton(tr("Create csv"));
		newCSVText = new QTextEdit();
		csvLayout->addWidget(newCSVNameLine,0,0,1,3);
		csvLayout->addWidget(newCSVText,1,0,1,3);
		csvLayout->addWidget(newCSVButton,2,2);
		connect(newCSVButton, SIGNAL(clicked()), this, SLOT(makeCSV()));
		csvDialog->setLayout(csvLayout);
		csvDialog->show();
	}
}

void MainWindow::makeCSV()
{
	/*!
	* Initiates saving of csv file and closes csv dialog when successfull.
	*/
	if(!(writeCSV(newCSVNameLine->text()))){
		QMessageBox::StandardButton msgBox;	
		msgBox = QMessageBox::critical(this, tr("Couldn't write csv file"),
		tr("Couldn't save csv file in csv dir."),
		QMessageBox::Ok);
	} else {
		csvDialog->close();	
	}

}

bool MainWindow::writeCSV(QString csvname)
{
	/*!
	* Opens csv.dat in read only mode.
	*/
	QString fileName=CSVDir;
	fileName.append("csv.dat");
	QFile file(fileName);
	QStringList lines;
	csvname.append(".csv");
	if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
        	return false;
	}else{
		QTextStream in(&file);
		in.setCodec("UTF-8");
		/*!
		* Reads entries of csv.dat and appends name of new csv file.
		*/
		while (!in.atEnd()) {
			lines << in.readLine();
		}
		lines << csvname;
		file.close();
	}

	/*!
	* Opens csv.dat in write only mode.
	*/
	if (!file.open(QIODevice::WriteOnly | QIODevice::Text)){
         	return false;
	}else{
		QTextStream out(&file);
		out.setCodec("UTF-8");
		/*!
		* Saves changes to csv.dat permanently.
		*/
		for(int i = 0; i < lines.size(); ++i){
			out << lines.at(i).toLocal8Bit().constData() << endl;
		}
		file.close();
	}
	/*!
	* Creates new csv file and opens it in write only mode.
	*/
	fileName=CSVDir;
	fileName.append(csvname);
	QFile file2(fileName);
	if (!file2.open(QIODevice::WriteOnly | QIODevice::Text)){
		return false;
	}else{
		/*!
		* Writes down changes to csv file permanently.
		*/
		QTextStream out(&file2);
		out.setCodec("UTF-8");
		out << newCSVText->toPlainText();
		return true;
	}
}


bool MainWindow::loadScenarioSetList()
{
	/*!
	* Opens scenariosets.dat in read only mode.
	*/
	QString fileName=ScenarioDir;
	fileName.append("scenariosets.dat");
	QFile file(fileName);
	if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
         return false;
	}else{
		QTextStream in(&file);
		in.setCodec("UTF-8");
		/*!
		* Adds entries of scenariosets.dat to scenario set list.
		*/
		while (!in.atEnd()) {
			QString line = in.readLine();
			shootScenarioSetSelect->addItem(line);
		}
		return true;
	}

}

bool MainWindow::loadMessagesHeaders(QString messageName)
{
	/*!
	* Opens selected message file in read only mode.
	*/
	QString fileName=MessageDir;
	fileName.append(messageSetSelect->currentText());
	fileName.append("/");
	fileName.append(messageTypeTemplateSelect->currentText());
	fileName.append("/");
	fileName.append(messageName);
	QFile file(fileName);
	if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
         return false;
	}else{
		headerFields->clear();
		QTextStream in(&file);
		in.setCodec("UTF-8");
		/*!
		* Displays content of selected message file.
		*/
		while (!in.atEnd()) {
			QString line = in.readLine();
			headerFields->append(line);
		}
		return true;
	}
}

bool MainWindow::writeMessagesHeaders(QString messageName)
{
	/*!
	* Opens message file in write only mode.
	*/
	QString fileName=MessageDir;
	fileName.append(messageSetSelect->currentText());
	fileName.append("/");
	fileName.append(messageTypeTemplateSelect->currentText());
	fileName.append("/");
	fileName.append(messageName);
	QFile file(fileName);
	if (!file.open(QIODevice::WriteOnly | QIODevice::Text)){
		return false;
	}else{
		QTextStream out(&file);
		out.setCodec("UTF-8");
		/*!
		* Saves changes to message.
		*/
		out << headerFields->toPlainText();
		return true;
	}
}


void MainWindow::viewMessage(){
	switch(messageTemplateSelect->currentIndex()){
		/*!
		* Checks if user chose to create a new message or view an existing message
		* via message list.
		*/
		case 0:
			break;
		case 1:
			makeCreateDialog(2);
			break;
		default:
			if(!(loadMessagesHeaders(messageTemplateSelect->currentText()))){
			QMessageBox::StandardButton msgBox;	
			msgBox = QMessageBox::critical(this, tr("Header not loaded"),
			tr("Couldn't find message file."),
			QMessageBox::Ok);
			}else{
				headerFields->setDisabled(false);
			}
	}
}

void MainWindow::saveMessage(){
	/*!
	* Inititates saving of changes to a message.
	*/
	if(messageTemplateSelect->currentIndex() > 1){
		if(!(writeMessagesHeaders(messageTemplateSelect->currentText()))){
		QMessageBox::StandardButton msgBox;	
		msgBox = QMessageBox::critical(this, tr("Header not saved"),
                      tr("Couldn't find message file."),
                      QMessageBox::Ok);
		}else{
			QMessageBox::StandardButton msgBox;	
			msgBox = QMessageBox::information(this, tr("Header saved"),
			tr("Changes to headers were successfully saved."),
                      	QMessageBox::Ok);
				headerFields->clear();
			messageTemplateSelect->setCurrentIndex(0);		
		}
	}
}

void MainWindow::viewMessageList(){
	/*!
	* Checks if user chose to create a new message type or load messages of an existing message type
	* via message type list.
	*/
	switch(messageTypeTemplateSelect->currentIndex()){
		case 0:
			break;
		case 1:
			makeCreateDialog(1);
			break;
		default:
			if(!(loadMessagesList())){
			QMessageBox::StandardButton msgBox;	
			msgBox = QMessageBox::critical(this, tr("Messages not loaded"),
                      	tr("Couldn't find messages.dat in message dir."),
                      	QMessageBox::Ok);
			}else{
				messageTemplateSelect->setDisabled(false);
			}
	}
}

void MainWindow::viewMessageTypeList(){
	/*!
	* Checks if user chose to create a new message set or load message types of an existing message set
	* via message set list.
	*/
	switch(messageSetSelect->currentIndex()){
		case 0:
			break;
		case 1:
			makeCreateDialog(0);
			break;
		default:
			if(!(loadMessageTypeList())){
			QMessageBox::StandardButton msgBox;	
			msgBox = QMessageBox::critical(this, tr("Message type list not loaded"),
                      	tr("Couldn't find messagetype.dat in selected message set dir."),
                      	QMessageBox::Ok);
			} else {
				messageTypeTemplateSelect->setDisabled(false);	
			}
	}
}

void MainWindow::makeSet()
{
	/*!
	* Initiates the creation of a new set.
	*/
	if(!(createSet(newMessageSetLine->text()))){
		QMessageBox::StandardButton msgBox;	
		msgBox = QMessageBox::critical(this, tr("New set not created"),
                      tr("Couldn't create set in messages dir."),
                      QMessageBox::Ok);
	}
	/*!
	* Realoads message list after a set was created.
	*/
	if(!(loadMessageSetList())){
		QMessageBox::StandardButton msgBox;	
		msgBox = QMessageBox::critical(this, tr("Couldn't update message set list"),
                      tr("Couldn't load message set list after modification."),
                      QMessageBox::Ok);
	}
	messageSetSelect->setCurrentIndex(messageSetSelect->count()-1);
	createDialog->close();
}
void MainWindow::makeType()
{
	/*!
	* Initiates the creation of a new message type.
	*/	
	if(!(createType(newMessageTypeLine->text()))){
		QMessageBox::StandardButton msgBox;	
		msgBox = QMessageBox::critical(this, tr("New type not created"),
                      tr("Couldn't create type in set dir."),
                      QMessageBox::Ok);
	}
	/*!
	* Reloads message type list after a new message type was created.
	*/
	if(!(loadMessageTypeList())){
		QMessageBox::StandardButton msgBox;	
		msgBox = QMessageBox::critical(this, tr("Couldn't update message type list"),
                      tr("Couldn't load type set list after modification."),
                      QMessageBox::Ok);
	}
	messageTypeTemplateSelect->setCurrentIndex(messageTypeTemplateSelect->count()-1);
	createDialog->close();
}
void MainWindow::makeMessage()
{
	/*!
	* Initiates the creation of a new message.
	*/	
	if(!(createMessage(newMessageTemplateLine->text()))){
		QMessageBox::StandardButton msgBox;	
		msgBox = QMessageBox::critical(this, tr("New message not created"),
                      tr("Couldn't create message in type dir."),
                      QMessageBox::Ok);
	}
	/*!
	* Reloads message list after a new message was created.
	*/
	if(!(loadMessagesList())){
		QMessageBox::StandardButton msgBox;	
		msgBox = QMessageBox::critical(this, tr("Couldn't update message list"),
                      tr("Couldn't load message list after modification."),
                      QMessageBox::Ok);
	}
	messageTemplateSelect->setCurrentIndex(messageTemplateSelect->count()-1);
	createDialog->close();
}

bool MainWindow::createSet(QString dirname){
	/*!
	* Opens messageset.dat in read only mode
	*/
	QString fileName=MessageDir;
	fileName.append("messageset.dat");
	QFile file(fileName);
	QStringList lines;
	if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
         return false;
	}else{
		QTextStream in(&file);
		in.setCodec("UTF-8");
		/*!
		* Reads entries of messageset.dat and appends a created setname.
		*/
		while (!in.atEnd()) {
			lines << in.readLine();
		}
		lines << dirname;
		file.close();
	}
	/*!
	* Opens messageset.dat in write only mode.
	*/
	if (!file.open(QIODevice::WriteOnly | QIODevice::Text)){
         return false;
	}else{
		QTextStream out(&file);
		out.setCodec("UTF-8");
		/*!
		* Writes down changes to messageset.dat.
		*/
		for(int i = 0; i < lines.size(); ++i){
			out << lines.at(i).toLocal8Bit().constData() << endl;
		}
		file.close();
	}
	/*!
	* Creates new messageset directory.
	*/
	QString setDirName=MessageDir;
	setDirName.append(dirname+"/");
	QDir myDir;
	if (!myDir.mkpath(setDirName)){
		return false;
	}
	/*!
	* Creates new messagetype.dat in new messageset directory.
	*/	
	setDirName.append("messagetype.dat");
	QFile file2(setDirName);
	if (!file2.open(QIODevice::WriteOnly | QIODevice::Text)){
		return false;
	}else{
		return true;
	}
}
bool MainWindow::createType(QString dirname){
	/*!
	* Opens messagetype.dat in read only mode.
	*/
	QString fileName=MessageDir;
	fileName.append(messageSetSelect->currentText());
	fileName.append("/messagetype.dat");
	QFile file(fileName);
	QStringList lines;
	if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
         return false;
	}else{
		QTextStream in(&file);
		in.setCodec("UTF-8");
		/*!
		* Reads entries of messagetype.dat and appends new type name.
		*/
		while (!in.atEnd()) {
			lines << in.readLine();
		}
		lines << dirname;
		file.close();
	}
	/*!
	* Opens messagetype.dat in write only mode.
	*/
	if (!file.open(QIODevice::WriteOnly | QIODevice::Text)){
         return false;
	}else{
		QTextStream out(&file);
		out.setCodec("UTF-8");
		/*!
		* Writes down changes to messagetype.dat.
		*/
		for(int i = 0; i < lines.size(); ++i){
			out << lines.at(i).toLocal8Bit().constData() << endl;
		}
		file.close();
	}
	/*!
	* Creates new message type directory.
	*/
	QString setDirName=MessageDir;
	setDirName.append(messageSetSelect->currentText());
	setDirName.append("/"+dirname+"/");
	QDir myDir;
	if (!myDir.mkpath(setDirName)){
		return false;
	}
	/*!
	* Creates an empty messages.dat in message type directory.
	*/
	setDirName.append("messages.dat");
	QFile file2(setDirName);
	if (!file2.open(QIODevice::WriteOnly | QIODevice::Text)){
		return false;
	}else{
		return true;
	}
}
bool MainWindow::createMessage(QString filename){
	/*!
	* Opens messages.dat in read only mode.
	*/
	QString fileName=MessageDir;
	fileName.append(messageSetSelect->currentText());
	fileName.append("/");
	fileName.append(messageTypeTemplateSelect->currentText());
	fileName.append("/");
	fileName.append("messages.dat");
	QFile file(fileName);
	QStringList lines;
	filename.append(".dat");
	if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
        	return false;
	}else{
		QTextStream in(&file);
		in.setCodec("UTF-8");
		/*!
		* Reads entries of messages.dat and appends new message name.
		*/
		while (!in.atEnd()) {
			lines << in.readLine();
		}
		lines << filename;
		file.close();
	}
	/*!
	* Opens messages.dat in write only mode.
	*/
	if (!file.open(QIODevice::WriteOnly | QIODevice::Text)){
         	return false;
	}else{
		QTextStream out(&file);
		out.setCodec("UTF-8");
		/*!
		* Writes down changes to messages.dat.
		*/
		for(int i = 0; i < lines.size(); ++i){
			out << lines.at(i).toLocal8Bit().constData() << endl;
		}
		file.close();
	}
	/*!
	* Creates empty message file in message directory
	*/
	fileName=MessageDir;
	fileName.append(messageSetSelect->currentText());
	fileName.append("/");
	fileName.append(messageTypeTemplateSelect->currentText());
	fileName.append("/");
	fileName.append(filename);
	QFile file2(fileName);
	if (!file2.open(QIODevice::WriteOnly | QIODevice::Text)){
		return false;
	}else{
		return true;
	}
}

